<template>
  <a-drawer
    :visible="visible"
    :title="title"
    placement="right"
    @close="btnCancel"
    :width="$store.getters.isMobile ? 350 : 1000"
    :keyboard="false"
    bodyStyle="background-color: #f6f7fb"
    :body-style="{
      height: 'calc(100% - 110px)',
      boxSizing: 'border-box',
      overflowY: 'auto',
    }"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      @finish="handleOk"
      layout="vertical"
    >
      <a-row :gutter="12">
        <!--客户信息添加 -->
        <a-col :span="$store.getters.isMobile ? 24 : 14">
          <div>客户信息</div>
          <a-card style="width: 100%">
            <a-row :gutter="16" :wrap="true">
              <a-col :span="$store.getters.isMobile ? 24 : 12">
                <a-form-item label="客户" name="name">
                  <a-input
                    v-model:value="formState.name"
                    placeholder="请填写客户"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="跟进人" name="followup_uid">
                  <!-- @search="followupSearch" -->
                  <a-auto-complete
                    v-model:value="formState.followup_uid"
                    :options="SeachFollow"
                    placeholder="请填写跟进人"
                    @search="followupSearch"
                    @select="
                      (value, option) => followupChange('followup_uid', option)
                    "
                  />
                </a-form-item>
              </a-col>
              <a-col :span="$store.getters.isMobile ? 24 : 12">
                <a-form-item label="行业" name="industry">
                  <a-select
                    v-model:value="formState.industry"
                    :options="industryOptions"
                    placeholder="请填选择行业"
                  >
                    <template #dropdownRender="{ menuNode: menu }">
                      <v-nodes :vnodes="menu" />
                      <a-divider style="margin: 4px 0" />

                      <!--@mousedown="e => e.preventDefault()"  -->
                      <div
                        style="
                          padding: 4px 8px;
                          cursor: pointer;
                          color: #1890ff;
                          text-align: center;
                        "
                        @mousedown="(e) => e.preventDefault()"
                        @click="addTag"
                      >
                        <!-- <plus-outlined /> -->
                        添加
                      </div>
                    </template>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="客户联系人" :name="['contacts', 'name']">
                  <a-input-group compact>
                    <a-input
                      style="width: 80px; background: #ebebeb"
                      placeholder="姓名"
                      v-model:value="formState.contacts.name"
                    />
                    <a-input
                      style="width: 158px"
                      placeholder="手机号"
                      :maxlength="11"
                      v-model:value="formState.contacts.phone"
                    />
                  </a-input-group>
                </a-form-item>
              </a-col>
              <a-col :span="$store.getters.isMobile ? 24 : 12">
                <a-form-item label="预计签约时间" name="expect_contract">
                  <a-date-picker
                    v-model:value="formState.expect_contract"
                    valueFormat="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="$store.getters.isMobile ? 24 : 12">
                <a-form-item label="需求数量/m²">
                  <a-input
                    v-model:value="formState.expect_area_min"
                    placeholder="最小值"
                    :style="{
                      width: $store.getters.isMobile ? '120px' : '112px',
                    }"
                    type="number"
                  />-
                  <a-input
                    v-model:value="formState.expect_area_max"
                    placeholder="最大值"
                    :style="{
                      width: $store.getters.isMobile ? '120px' : '112px',
                    }"
                    type="number"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="$store.getters.isMobile ? 24 : 12">
                <a-form-item label="来访时间" name="visit_time">
                  <a-date-picker
                    v-model:value="formState.visit_time"
                    valueFormat="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="$store.getters.isMobile ? 24 : 12">
                <a-form-item label="客户状态">
                  <a-select
                    v-model:value="formState.status"
                    :options="statusOptions"
                    placeholder="请选择客户装态"
                  ></a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-form-item label="来访渠道" name="source">
              <a-select
                v-model:value="formState.source"
                :options="sourceOptions"
                placeholder="请选来访渠道"
              ></a-select>
            </a-form-item>
            <a-form-item label="渠道联系人" name="channel_id">
              <a-select
                v-model:value="formState.channel_id"
                :options="channelList"
                placeholder="请选择渠道联系人"
              ></a-select>
            </a-form-item>
            <a-form-item label="备注">
              <a-textarea
                v-model:value="formState.remark"
                placeholder="请填写备注信息"
                :rows="4"
              />
            </a-form-item>
            <a-row :gutter="16" :wrap="true">
              <a-col :span="18">
                <a-form-item label="成交几率">
                  <Slider
                    :tip-formatter="formatter"
                    v-model:value="formState.deal_precent"
                    @change="formatterChange"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6" style="line-height: 100px">
                {{ formatterValue }}%
              </a-col>
            </a-row>
          </a-card>
        </a-col>
        <!-- 房源添加 -->
        <a-col style="height: 830px" :span="$store.getters.isMobile ? 24 : 10">
          <a-card title="意向房源">
            <ChooseHousingResources
              v-if="visible"
              limitType="village"
              :areaEmptyDisabled="false"
              :defaultChecked="{ roomList }"
              @request="$utils.commonRequest"
              @getResult="getRoomList"
            />
          </a-card>
        </a-col>
      </a-row>

      <div class="drawer-footer">
        <a-button class="clear mr-10" @click="btnCancel">取消</a-button>
        <a-button type="primary" html-type="submit">确定</a-button>
      </div>
    </a-form>
    <!-- 行业分类 -->
    <EditTag
      @closeTag="editTagClose"
      @success="editSuccess"
      :visible="editVisible"
    ></EditTag>
    <!-- 行业分类 -->
  </a-drawer>
</template>

<script>
import {
  defineComponent,
  ref,
  toRaw,
  reactive,
  computed,
  watch,
  createVNode,
} from "vue";
import { ChooseHousingResources } from "bl-common-vue3";
import { message, Slider, Modal } from "ant-design-vue";
import store from "../../../../store";
import request from "../../../../common/utils/request";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import EditTag from "./EditTag.vue";
import { useRouter } from "vue-router";
export default defineComponent({
  name: "CustomerListLayer",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [Number, String],
      default: 0,
    },
  },
  components: {
    Slider,
    EditTag,
    ChooseHousingResources,
    VNodes: (_, { attrs }) => {
      return attrs.vnodes;
    },
  },
  setup(props, context) {
    const $router = useRouter();
    const btnCancel = () => {
      context.emit("cancel");
      formRef.value.resetFields();
      formState.status = [];
      add.value = 0;
    };
    const roomList = ref([]);
    const getRoomList = (info) => {
      roomList.value = info.roomList;
    };
    const formRef = ref();
    const handleOk = () => {
      if (formState.contacts.phone.length !== 11) {
        message.warn("手机号不足11位，请重新填写");
        return;
      }

      add.value = 0;
      let params = JSON.parse(JSON.stringify(formState));
      for (let key in followup) {
        params[key] = followup[key];
      }
      params.house_resource = roomList.value.map((item) => ({
        id: item.id,
        room_name: item.title,
        layer_id: item.extra.layer_id,
        layer_name: item.extra.layer_name,
        build_id: item.extra.build_id,
        build_name: item.extra.build_name,
        village_id: item.extra.village_id,
        village_name: item.extra.village_name,
      }));

      // if (!statusID) {
      //   params.status = formState.status;
      // }
      params.industry = formState.industry;
      if (!formState.followup_uid) {
        params.followup_uid = "";
      }
      if (props.id) {
        params.id = props.id;
        request.put("/org", "/business/customer", params).then((res) => {
          context.emit("btnOk");
          formRef.value.resetFields();
          message.success("修改成功");
          formState.status = [];
        });
        return;
      }
      request.post("/org", "/business/customer", params).then((res) => {
        context.emit("btnOk");
        formRef.value.resetFields();
        message.success("添加成功");
        formState.status = [];
      });
    };
    //  客户信息添加表单
    const formState = reactive({
      name: "", //名称
      industry: undefined, // 行业
      followup_uid: "", //跟进人
      contacts: {
        name: "",
        phone: "",
      }, //联系人信息
      expect_contract: "", //预约签约时间
      expect_area_min: "", //需求数量最小值
      expect_area_max: "", // 需求数量最大值
      visit_time: "", //来访时间
      status: [], //客户装态
      source: "", //来访渠道
      channel_id: undefined, //渠道联系人 联系人接口 传ID
      remark: "", //备注
      deal_precent: "", //成交几率
      id: "",
    });
    const rules = {
      name: [
        {
          required: true,
          message: "请输入租客姓名",
          trigger: "blur",
        },
      ],
      industry: [
        {
          required: false,
          message: "请选择行业",
          // trigger: "change",
        },
      ],
      contacts: {
        name: [
          {
            required: true,
            message: "请输入客户联系人",
          },
        ],
        phone: [
          {
            required: true,
            message: "请输入客户联系人",
          },
        ],
      },
      expect_contract: [
        {
          required: false,
          message: "请选择预计签约时间",
        },
      ],
      expect_area: [
        {
          required: true,
          message: "请填写需求数量",
          trigger: "blur",
          type: "number",
        },
      ],
      visit_time: [
        {
          required: false,
          message: "请选择来访时间",
          trigger: "blur",
        },
      ],
      status: [
        {
          required: true,
          message: "请选择客户状态",
          trigger: "blur",
        },
      ],
      source: [
        {
          required: true,
          message: "请输入来访渠道",
          trigger: "blur",
        },
      ],
      // channel_id: [
      //   {
      //     required: true,
      //     message: "请输入渠道联系人",
      //     trigger: "blur",
      //   },
      // ],
      remark: [
        {
          required: true,
          message: "请输入备注信息",
          trigger: "blur",
        },
      ],
    };
    // 来访渠道
    const sourceOptions = ref([]);
    // 来访渠道列表
    const sourceOptionsList = () => {
      request.get("/org", "/business/customer/source").then((res) => {
        sourceOptions.value = res.list.map((item) => {
          return {
            value: item.key,
            label: item.name,
          };
        });
        formState.source = res.list[0].key;
      });
    };
    //  客户装态
    const statusOptions = ref([]);
    // const statysId = ref(0);
    // 客户状态请求
    const statusOptionsList = () => {
      request.get("/org", "/business/customer/status").then((res) => {
        statusOptions.value = res.list.map((item) => {
          return {
            value: item.key,
            label: item.name,
          };
        });
        formState.status = res.list[0].key;
        // statysId.value = res.list[0].key;
      });
    };
    statusOptionsList();
    // 成交几率
    const formatter = (value) => {
      return `${value}%`;
    };
    const formatterValue = ref(0);
    const formatterChange = (value) => {
      formatterValue.value = value;
    };
    // 添加行业标签
    const editVisible = ref(false);
    const addTag = () => {
      console.log("添加");
      editVisible.value = true;
    };
    const editTagClose = () => {
      editVisible.value = false;
    };
    const add = ref(0);
    const editSuccess = () => {
      editTagClose();
      industryList();
      add.value = 1;
    };
    // 行业分类
    const industryOptions = ref([]);
    const industryList = () => {
      request.get("/org", "/manage/taglib/industry/all").then((res) => {
        if (res.list.length) {
          if (add.value == 1) {
            formState.industry = res.list[0].id;
          }
          industryOptions.value = res.list.map((item) => {
            return {
              value: item.id,
              label: item.name,
              id: item.id,
            };
          });
        } else {
          Modal.confirm({
            title: () => "提示",
            content: () => "您需要先添加行业分类才能继续添加客户",
            icon: () => createVNode(ExclamationCircleOutlined),
            centered: true,
            okText: () => "前往",
            onOk() {
              $router.push({
                name: "taglibIndustry",
              });

              context.emit("cancel");
            },
            onCancel() {
              context.emit("cancel");
            },
          });
        }
      });
    };

    // 客户装态
    // let statusID = null;
    // const StatusyChange = (key, option) => {
    //   statysList[key] = option.id;
    //   statusID = option.id;
    // };

    //  联系人
    const channelList = ref([]);
    const searchList = () => {
      request.get("/org", "/business/customer/channel").then((res) => {
        channelList.value = res.list.map((item) => ({
          value: item.id,
          label: item.name,
        }));
      });
    };

    // 跟进人
    const SeachFollow = ref([]);
    const followList = (text) => {
      request
        .get("/org", "/user/getAdminList", { keyword: text })
        .then((res) => {
          SeachFollow.value = res.list.map((itme) => {
            return {
              value: itme.realname,
              label: itme.realname,
              uid: itme.uid,
            };
          });
        });
    };
    let followup = {};
    let timeouts = null;
    let current = "";
    const followupChange = (key, option) => {
      followup[key] = option.uid;
    };
    const followupSearch = (searchText) => {
      getCurrents(searchText, (result) => (SeachFollow.value = result));
    };
    const getCurrents = (value, callback) => {
      if (timeouts) {
        clearTimeout(timeouts);
        timeouts = null;
      }
      current = value;
      const searchList = () => {
        request
          .get("/org", "/user/getAdminList", { keywords: value })
          .then((res) => {
            if (current === value) {
              let result = [];
              if (res.list) {
                result = res.list.map((item) => ({
                  value: item.realname,
                  label: item.realname,
                  uid: item.uid,
                }));
              }
              callback(result);
            }
          });
      };
      timeouts = setTimeout(searchList, 300);
    };

    // 详情
    let detail = {};
    const industryID = ref({});
    const flolow = ref({});
    const getcustomer = () => {
      request
        .get("/org", "/business/customer/detail", { id: props.id })
        .then((res) => {
          detail = res.detail;
          if (!detail.contacts.phone) {
            detail.contacts.name = "";
            detail.contacts.phone = "";
          }
          setModelRef(detail);
          if (detail.house_resource) {
            roomList.value = detail.house_resource;
          }

          formState.status = Number(detail.status);
          // autoFillState.channel_id = detail.channel_id;
          // formState.channel_id = detail.channel_name;
          formatterValue.value = detail.deal_precent;
          followup.followup_uid = detail.followup_uid;
          if (detail.followup_uid == 0) {
            formState.followup_uid = "";
            return;
          }
          flolow.value = SeachFollow.value.find((item) => {
            return item.uid == Number(detail.followup_uid);
          });
          formState.followup_uid = flolow.value.label;

          industryID.value = industryOptions.value.find((item) => {
            return item.value == Number(detail.industry);
          });
          if (industryID.value == undefined) {
            formState.industry = null;
            return;
          }
          formState.industry = industryID.value.value;
        });
    };

    const setModelRef = (state) => {
      for (let key in state) {
        formState[key] = state[key];
      }
    };
    // 跟进人
    const value = ref("");
    const title = computed(() => {
      return props.id ? "编辑客户" : "新建客户";
    });

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          statusOptionsList();
          industryList();
          sourceOptionsList();
          followList();
          searchList();
          if (props.id) {
            getcustomer();
          }
          return;
        }
        console.log("弹窗关闭");
        formState.expect_area_min = "";
        formState.expect_area_max = "";
        formState.deal_precent = "";
        formatterValue.value = 0;
        value.value = "";
        formState.contacts.phone = "";
        formState.followup_uid = "";
        formState.channel_id = undefined;
        roomList.value = [];
      }
    );

    return {
      formatterValue,
      title,
      formRef,
      industryOptions,
      value,
      sourceOptions,
      statusOptions,
      channelList,
      formState,
      rules,
      btnCancel,
      handleOk,
      formatter,
      formatterChange,
      addTag,
      editVisible,
      editSuccess,
      editTagClose,
      followupSearch,
      SeachFollow,
      followupChange,
      getRoomList,
      roomList,
    };
  },
});
</script>

<style lang="less" scoped>
.footer {
  position: fixed;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #f0f0f0;
  height: 70px;
  background-color: #fff;
  .btn {
    margin-left: 750px;
    margin-top: 20px;
  }
  .clear {
    margin-right: 20px;
  }
}

input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
</style>
